package com.efb.module.ui.search

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.databinding.ObservableInt
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DividerItemDecoration
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.inspector.app.R
import com.inspector.app.databinding.MapsearchFragBinding
import com.inspector.app.di.location.CustomCoordinateType
import com.inspector.app.di.util.UI
import com.inspector.app.ui.flight.FlightFragment
import com.inspector.app.ui.flight.mapsearch.poi.GDSearchInstance
import com.inspector.app.ui.flight.mapsearch.poi.TDMapInstance
import com.inspector.app.ui.flight.mapsearch.MapSearchAdapter
import com.inspector.app.ui.flight.mapsearch.MapSearchInstance
import com.inspector.app.ui.flight.mapsearch.MapSearchLayerInstance
import com.inspector.app.ui.flight.mapsearch.poi.MapSearchPoi
import com.inspector.app.ui.plot.PlotFragment
import com.inspector.app.ui.widget.InputFilterMinMax
import com.inspector.app.util.CommonUtil
import com.inspector.app.util.ConstantUtil
import com.inspector.app.util.CoordinateTransformUtils
import com.inspector.app.util.LocationUtils
import com.inspector.app.util.LogUtil
import com.inspector.app.util.ScreenUtils
import com.inspector.app.util.SharedPreferencesUtils
import com.inspector.app.util.ToastUtil
import com.mapsforge.map.vtm.AppExecutors
import java.io.*
import java.lang.ref.WeakReference
import kotlin.text.*


/**
 * 地图搜索弹窗
 * @author pank 2023/3/30
 */
class MapSearchFragment : DialogFragment() {

    private val TAG = "MapSearchFragment"
    private var _binding: MapsearchFragBinding? = null
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setStyle(STYLE_NORMAL, R.style.mapsearch_dialog_style)
        setStyle(STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar_Fullscreen)
    }

    override fun onStart() {
        super.onStart()
        initAttributes()
    }

    //[根据飞行状态栏动态调整高度]
    private fun initAttributes() {
        try {
            val window = dialog?.window ?: return
            //判断如果是手机端 宽度全占满
            //[设置弹窗宽高]
            if (!CommonUtil.isTabletDevice(requireContext())) {
                val width = ScreenUtils.getScreenWidth(requireContext())
                window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT)
            } else {
                val width =
                    ScreenUtils.getScreenWidth(requireContext()) * 0.7f + UI.dpToPx(30)
                window.setLayout(width.toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
            }
            val attributes = window.attributes
            attributes.y = UI.dpToPx(126)
            attributes.gravity = Gravity.TOP
            window.attributes = attributes
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //[设置外部可触摸]
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCanceledOnTouchOutside(false)
        dialog.window?.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
        return dialog
    }

    //[搜索列表]
    private val searchAdapter by lazy {
        MapSearchAdapter(mapSearchFragment = this)
    }

    //[当前选中tab类型]
    private val checkedType = ObservableInt(0)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = MapsearchFragBinding.inflate(inflater, container, false)
        setupView()
        return binding.root
    }


    private fun setupView() {
        //[高德、百度-隐私政策合规]
        GDSearchInstance.instance.updatePrivacy(requireContext())
        val itemDecoration = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
        itemDecoration.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.divier_grey)!!)
        binding.itemRecyclerView.adapter = searchAdapter
        binding.itemRecyclerView.addItemDecoration(itemDecoration)
        binding.checkedType = checkedType
        binding.handler = this
        binding.lifecycleOwner = viewLifecycleOwner
        binding.executePendingBindings()

        //[初始化图层布局]
        if (parentFragment is FlightFragment) {
            MapSearchLayerInstance.getInstance().setupView(requireContext(), (parentFragment as FlightFragment).dMap)
        } else if (parentFragment is PlotFragment) {
            MapSearchLayerInstance.getInstance().setupView(requireContext(), (parentFragment as PlotFragment).dMap)
        } else throw IllegalStateException("需要引用地图")


        //[点击软键盘-搜索按钮]
        binding.etMapSearchDegreeLat.setOnEditorActionListener()
        binding.etMapSearchMinuteLat.setOnEditorActionListener()
        binding.etMapSearchSecondLat.setOnEditorActionListener()
        binding.etMapSearchDegreeLng.setOnEditorActionListener()
        binding.etMapSearchMinuteLng.setOnEditorActionListener()
        binding.etMapSearchSecondLng.setOnEditorActionListener()

        binding.editTextDLat.setOnEditorActionListener()
        binding.editTextDLng.setOnEditorActionListener()

        binding.editTextDFDLat.setOnEditorActionListener()
        binding.editTextDFFLat.setOnEditorActionListener()
        binding.editTextDFDLng.setOnEditorActionListener()
        binding.editTextDFFLng.setOnEditorActionListener()

        //[点击软键盘-通过名称搜索]
        binding.etMapSearchName.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchByName(needTips = true)
            }
            true
        }

        binding.rbSearchLatLng.inlineCompoundDrawable(R.drawable.mapsearch_indicator)

        binding.editTextDFDLat.inputFilterMinMax(0, 90, tips = "请输入有效的纬度范围")
        binding.etMapSearchDegreeLat.inputFilterMinMax(0, 90, tips = "请输入有效的纬度范围")
        binding.editTextDFDLng.inputFilterMinMax(0, 180, tips = "请输入有效的经度范围")
        binding.etMapSearchDegreeLng.inputFilterMinMax(0, 180, tips = "请输入有效的经度范围")
    }


    //[限制输入框输入范围]
    private fun EditText.inputFilterMinMax(min: Int, max: Int, tips: String) {
        this.filters = arrayOf(InputFilterMinMax(min, max, tips))
    }

    private fun RadioButton.inlineCompoundDrawable(drawRes: Int) {
        val drawable =
            ContextCompat.getDrawable(requireContext(), drawRes) ?: return
        drawable.setBounds(0, -UI.dpToPx(3), drawable.intrinsicWidth, 0)
        this.setCompoundDrawables(null, null, null, drawable)
    }


    fun search() {
        //点击搜索显示
        searchByName(needTips = false)
    }

    //[输入文件监听]
    fun afterTextChanged(text: Editable, id: Int) {
        if (updateText) return //[避免重复调用卡死]
        updateText = true

        when (id) {
            R.id.et_map_search_name -> { //[名称搜索]
                searchByName(needTips = false)
            }

            //[输满自动聚焦到下一段文本输入框]
            R.id.et_map_search_degree_lat -> {
                if (text.toString().length == 2 && binding.etMapSearchDegreeLat.hasFocus()) {
                    binding.etMapSearchMinuteLat.requestFocus()
                }
            }

            R.id.et_map_search_minute_lat -> {
                if (text.toString().length == 2 && binding.etMapSearchMinuteLat.hasFocus()) {
                    binding.etMapSearchSecondLat.requestFocus()
                }
            }

            R.id.et_map_search_second_lat -> {
                if (text.toString().length == 2 && binding.etMapSearchSecondLat.hasFocus()) {
                    binding.etMapSearchDegreeLng.requestFocus()
                }
            }

            R.id.et_map_search_degree_lng -> {
                if (text.toString().length == 3 && binding.etMapSearchDegreeLng.hasFocus()) {
                    binding.etMapSearchMinuteLng.requestFocus()
                }
            }

            R.id.et_map_search_minute_lng -> {
                if (text.toString().length == 2 && binding.etMapSearchMinuteLng.hasFocus()) {
                    binding.etMapSearchSecondLng.requestFocus()
                }
            }

            R.id.et_map_search_second_lng -> {
                /*if (text.toString().isNotEmpty()) {
                    searchByLatLng(needTips = false)
                }*/
            }

            // 2023/12/26 [新增度分搜索]
            R.id.editTextDFDLat -> {
                if (text.toString().length == 2 && binding.editTextDFDLat.hasFocus()) {
                    binding.editTextDFFLat.requestFocus()
                }
            }

            R.id.editTextDFFLat -> {
                binding.editTextDFFLat.formatMS(text.toString())
            }

            R.id.editTextDFDLng -> {
                if (text.toString().length == 3 && binding.editTextDFDLng.hasFocus()) {
                    binding.editTextDFDLng.requestFocus()
                }
            }

            R.id.editTextDFFLng -> {
                binding.editTextDFFLng.formatMS(text.toString())
            }

            // 2023/12/26 [新增度搜索]
            R.id.editTextDLat -> {
                binding.editTextDLat.formatDD(text.toString(), 90, true)
            }

            R.id.editTextDLng -> {
                binding.editTextDLng.formatDD(text.toString(), 180, false)
            }
        }

        // [同步其它文本框]
        syncEDValue(id)
        updateText = false
    }


    private val formatString = "%.4f"
    private var updateText = false
    private fun syncEDValue(id: Int) {
        try {
            when (id) {
                R.id.editTextDLat -> {
                    val text = binding.editTextDLat.text.toString()
                    if (text.isEmpty()) return
                    val d2Dm = LocationUtils.D2Dm(text.toDouble(), formatString)
                    val secondDegree = d2Dm.split("°")[0]
                    val secondM = d2Dm.split("°")[1].replace("′", "")
                    binding.editTextDFDLat.text =
                        Editable.Factory.getInstance().newEditable(secondDegree)
                    binding.editTextDFFLat.text = Editable.Factory.getInstance()
                        .newEditable(formatDoubleValue(secondM.toDouble(), 4))

                    val d2DmsStrs = LocationUtils.D2DmsStrs(text.toDouble(), formatString)
                    binding.etMapSearchDegreeLat.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[0])
                    binding.etMapSearchMinuteLat.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[1])
                    binding.etMapSearchSecondLat.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[2])
                }

                R.id.editTextDLng -> {
                    val text = binding.editTextDLng.text.toString()
                    if (text.isEmpty()) return
                    val d2Dm = LocationUtils.D2Dm(text.toDouble(), formatString)
                    val secondDegree = d2Dm.split("°")[0]
                    val secondM = d2Dm.split("°")[1].replace("′", "")
                    binding.editTextDFDLng.text =
                        Editable.Factory.getInstance().newEditable(secondDegree)
                    binding.editTextDFFLng.text = Editable.Factory.getInstance()
                        .newEditable(formatDoubleValue(secondM.toDouble(), 4))

                    val d2DmsStrs = LocationUtils.D2DmsStrs(text.toDouble(), formatString)
                    binding.etMapSearchDegreeLng.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[0])
                    binding.etMapSearchMinuteLng.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[1])
                    binding.etMapSearchSecondLng.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[2])
                }

                R.id.editTextDFDLat, R.id.editTextDFFLat -> {
                    if (binding.editTextDFDLat.text.toString().isEmpty()) return
                    if (binding.editTextDFFLat.text.toString().isEmpty()) return
                    val transformDms = LocationUtils.transform_dms(
                        binding.editTextDFDLat.text.toString().toDouble(),
                        binding.editTextDFFLat.text.toString().toDouble()
                    )

                    val dms2D =
                        LocationUtils.Dms2D(transformDms[0], transformDms[1], transformDms[2])
                    binding.editTextDLat.text =
                        Editable.Factory.getInstance().newEditable(formatDoubleValue(dms2D, 6))

                    val d2DmsStrs = LocationUtils.D2DmsStrs(dms2D, formatString)
                    binding.etMapSearchDegreeLat.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[0])
                    binding.etMapSearchMinuteLat.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[1])
                    binding.etMapSearchSecondLat.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[2])
                }

                R.id.editTextDFDLng, R.id.editTextDFFLng -> {
                    if (binding.editTextDFDLng.text.toString().isEmpty()) return
                    if (binding.editTextDFFLng.text.toString().isEmpty()) return
                    val transformDms = LocationUtils.transform_dms(
                        binding.editTextDFDLng.text.toString().toDouble(),
                        binding.editTextDFFLng.text.toString().toDouble()
                    )

                    val dms2D =
                        LocationUtils.Dms2D(transformDms[0], transformDms[1], transformDms[2])
                    binding.editTextDLng.text = Editable.Factory.getInstance().newEditable(
                        formatDoubleValue(dms2D, 6)
                    )

                    val d2DmsStrs = LocationUtils.D2DmsStrs(dms2D, formatString)
                    binding.etMapSearchDegreeLng.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[0])
                    binding.etMapSearchMinuteLng.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[1])
                    binding.etMapSearchSecondLng.text =
                        Editable.Factory.getInstance().newEditable(d2DmsStrs[2])
                }

                R.id.et_map_search_degree_lat, R.id.et_map_search_minute_lat, R.id.et_map_search_second_lat -> {
                    if (binding.etMapSearchDegreeLat.text.toString().isEmpty() ||
                        binding.etMapSearchMinuteLat.text.toString().isEmpty() ||
                        binding.etMapSearchSecondLat.text.toString().isEmpty()
                    ) return

                    val dms2D = LocationUtils.Dms2D(
                        binding.etMapSearchDegreeLat.text.toString(),
                        binding.etMapSearchMinuteLat.text.toString(),
                        binding.etMapSearchSecondLat.text.toString(),
                        true
                    )
                    binding.editTextDLat.text = Editable.Factory.getInstance().newEditable(
                        formatDoubleValue(dms2D, 6)
                    )

                    val d2Dm = LocationUtils.D2Dm(dms2D, formatString)
                    val secondDegree = d2Dm.split("°")[0]
                    val secondM = d2Dm.split("°")[1].replace("′", "")
                    binding.editTextDFDLat.text =
                        Editable.Factory.getInstance().newEditable(secondDegree)
                    binding.editTextDFFLat.text =
                        Editable.Factory.getInstance().newEditable(secondM)
                }

                R.id.et_map_search_degree_lng, R.id.et_map_search_minute_lng, R.id.et_map_search_second_lng -> {
                    if (binding.etMapSearchDegreeLng.text.toString().isEmpty() ||
                        binding.etMapSearchMinuteLng.text.toString().isEmpty() ||
                        binding.etMapSearchSecondLng.text.toString().isEmpty()
                    ) return

                    val dms2D = LocationUtils.Dms2D(
                        binding.etMapSearchDegreeLng.text.toString(),
                        binding.etMapSearchMinuteLng.text.toString(),
                        binding.etMapSearchSecondLng.text.toString(),
                        false
                    )
                    binding.editTextDLng.text = Editable.Factory.getInstance().newEditable(
                        formatDoubleValue(dms2D, 6)
                    )

                    val d2Dm = LocationUtils.D2Dm(dms2D, formatString)
                    val secondDegree = d2Dm.split("°")[0]
                    val secondM = d2Dm.split("°")[1].replace("′", "")
                    binding.editTextDFDLng.text =
                        Editable.Factory.getInstance().newEditable(secondDegree)
                    binding.editTextDFFLng.text = Editable.Factory.getInstance()
                        .newEditable(formatDoubleValue(secondM.toDouble(), 4))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun formatDoubleValue(doubleValue: Double, count: Int): String {
        return CommonUtil.formatDouble(doubleValue, count)
    }


    //[第二排分格式化]
    private fun EditText.formatMS(text: String) {
        try {
            if (text.contains(".")) {
                //[继续输入]
                if (text.startsWith(".") || text.endsWith(".")) return

                val doubleValue = text.toDouble()
                if (doubleValue > 60) {
                    this.text = Editable.Factory.getInstance().newEditable("60")
                    this.setSelection(this.text.length)
                    if (this.hasFocus()) {
                        ToastUtil.getInstance().showToast("度分秒格式中，分值不应超过60！")
                    }
                    return
                }

                //[满足条件截取]
                if (text.split(".")[1].length <= 4) return
                val formatLatLng = formatDoubleValue(doubleValue, 4)
                this.text = Editable.Factory.getInstance().newEditable(formatLatLng)
                this.setSelection(this.text.length)
                if (this.hasFocus()) {
                    ToastUtil.getInstance().showToast("小数点后保留四位")
                }
                return
            }

            if (text.toInt() > 60) {
                this.text = Editable.Factory.getInstance().newEditable("60")
                this.setSelection(this.text.length)
                ToastUtil.getInstance().showToast("度分秒格式中，分值不应超过60！")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //[第一排度格式化]
    private fun EditText.formatDD(text: String, maxNum: Int, latDegree: Boolean) {
        try {
            if (text.contains(".")) {
                //[继续输入]
                if (text.startsWith(".") || text.endsWith(".")) return

                val doubleValue = text.toDouble()
                if (doubleValue > maxNum) {
                    this.text = Editable.Factory.getInstance().newEditable(maxNum.toString())
                    this.setSelection(this.text.length)
                    if (this.hasFocus()) {
                        if (latDegree) {
                            ToastUtil.getInstance().showToast("请输入有效的纬度范围！")
                        } else {
                            ToastUtil.getInstance().showToast("请输入有效的经度范围！")
                        }
                    }
                    return
                }

                //[满足条件截取]
                if (text.split(".")[1].length <= 6) return
                val formatLatLng = formatDoubleValue(doubleValue, 6)
                this.text = Editable.Factory.getInstance().newEditable(formatLatLng)
                this.setSelection(this.text.length)
                if (this.hasFocus()) {
                    ToastUtil.getInstance().showToast("小数点后保留六位")
                }
                return
            }

            if (text.toInt() > maxNum) {
                this.text = Editable.Factory.getInstance().newEditable(maxNum.toString())
                this.setSelection(this.text.length)
                if (latDegree) {
                    ToastUtil.getInstance().showToast("请输入有效的纬度范围！")
                } else {
                    ToastUtil.getInstance().showToast("请输入有效的经度范围！")
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    //[点击软键盘-搜索按钮]
    private fun EditText.setOnEditorActionListener() {
        setOnEditorActionListener { textView, actionId, keyEvent ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchByLatLng(needTips = true)
            }
            true
        }
    }


    //[点击tab-切换搜索类型]
    fun onCheckedChanged(radioGroup: RadioGroup, id: Int) {
        val checked = radioGroup.findViewById<RadioButton>(id)
        val clickPosition = radioGroup.indexOfChild(checked)
        checkedType.set(clickPosition)

        // [2023/12/26 新增指示器]
        for (i in 0 until radioGroup.childCount) {
            val radioButton = radioGroup.getChildAt(i)
            if (radioButton !is RadioButton) continue
            if (i != clickPosition) {
                radioButton.inlineCompoundDrawable(R.drawable.mapsearch_indicator_default)
                continue
            }
            radioButton.inlineCompoundDrawable(R.drawable.mapsearch_indicator)
        }

        //[动态切换数字和文本键盘]
        dialog?.currentFocus?.clearFocus()
        if (checkedType.get() == 0) {
            binding.etMapSearchDegreeLat.post {
                binding.etMapSearchDegreeLat.requestFocus()
                binding.etMapSearchDegreeLat.inputType = InputType.TYPE_CLASS_NUMBER
            }
        } else {
            binding.etMapSearchName.text = Editable.Factory.getInstance().newEditable("")
            binding.etMapSearchName.post {
                binding.etMapSearchName.requestFocus()
                binding.etMapSearchName.inputType = InputType.TYPE_CLASS_TEXT
            }
        }

        //[切换重置列表]
        updatePoiItems(null)
    }


    //[点击删除，清空当前搜索的文本]
    fun clearSearchText() {
        showCloseDialog()
    }


    //[是否需要展示关闭弹窗???]
    private var closeDialog: AlertDialog? = null
    private fun showCloseDialog() {
        closeDialog?.dismiss()
        closeDialog = null
        closeDialog = AlertDialog.Builder(requireActivity())
            .setMessage("是否清空当前搜索内容?")
            .setNegativeButton("取消", null)
            .setPositiveButton("确定") { _, _ ->
//                clearEDText()
                //[隐藏键盘]
                CommonUtil.hideKeyboard(dialog)

                //[清除图层以及列表显示]
                MapSearchLayerInstance.getInstance().clearMapLayer()
                updatePoiItems(null)
                this@MapSearchFragment.dismissAllowingStateLoss()
            }.create()
        closeDialog?.show()
        closeDialog?.getButton(android.app.AlertDialog.BUTTON_NEGATIVE)?.setTextColor(
            ContextCompat.getColor(requireContext(), R.color.colorPointOk)
        )
        closeDialog?.getButton(android.app.AlertDialog.BUTTON_POSITIVE)?.setTextColor(
            ContextCompat.getColor(requireContext(), R.color.colorPointOk)
        )
    }


    //[根据名称搜索]
    private fun searchByName(needTips: Boolean) {
        val searchText = binding.etMapSearchName.text.toString()
        if (searchText.isEmpty()) {
            updatePoiItems(null)
            if (needTips) {
                ToastUtil.getInstance().showToast("请输入搜索关键字")
            }
            return
        }

        binding.listRootView.visibility = View.VISIBLE
        binding.itemTips.visibility = View.VISIBLE
        if (checkedType.get() == 1) {
            when (SharedPreferencesUtils.getInt(ConstantUtil.USERID, ConstantUtil.MapSearchEngine, 1)) {
                1 -> { //[在线搜索-高德]
                    GDSearchInstance.instance.getPoiSearch(requireContext(), keyWord = searchText) { poiItems ->
                        updatePoiItems(poiItems)
                    }
                }

                /*2 -> { //[在线搜索-百度]
                    BDSearchInstance.instance.getPoiSearch(
                        requireContext(),
                        keyWord = searchText) { poiItems ->
                        updatePoiItems(poiItems)
                    }
                }*/

                else -> { //[在线搜索-天地图]
                    TDMapInstance.instance.getPoiSearch(fragment = this, keyWord = searchText) { poiItems ->
                        updatePoiItems(poiItems)
                    }
                }
            }
        } else {//[图层搜索-搜标绘、机场、VOR、NDB、航路点]
            /*AppExecutors.getInstance().diskIO().execute {
                val searchItems = MapSearchInstance.getInstance().searchItemsByText(searchText)
                AppExecutors.getInstance().mainThread().execute {
                    updatePoiItems(searchItems)
                    if (needTips && searchItems.isNullOrEmpty()) {
                        ToastUtil.getInstance().showToast("暂无搜索数据,请您换个关键字试试")
                    }
                }
            }*/
        }
    }


    //[更新列表]
    private fun updatePoiItems(searchItems: MutableList<MapSearchPoi>?) {
        if (_binding?.itemRecyclerView == null) return
        searchItems?.forEach { it.tabType = checkedType.get() }
        searchAdapter.submitList(searchItems)
        if (!searchItems.isNullOrEmpty()) {
            binding.itemRecyclerView.post {
                binding.itemRecyclerView.scrollToPosition(0)
            }
            binding.itemTips.visibility = View.GONE
        } else {
            binding.listRootView.visibility = View.GONE
            binding.itemTips.visibility = View.GONE
        }
    }


    //[根据经纬度搜索]
    @Suppress("UNREACHABLE_CODE")
    private fun searchByLatLng(needTips: Boolean) {
        if (binding.etMapSearchDegreeLat.text.toString().isEmpty()
            || binding.etMapSearchMinuteLat.text.toString().isEmpty()
            || binding.etMapSearchSecondLat.text.toString().isEmpty()
            || binding.etMapSearchDegreeLng.text.toString().isEmpty()
            || binding.etMapSearchMinuteLng.text.toString().isEmpty()
            || binding.etMapSearchSecondLng.text.toString().isEmpty()

            || binding.editTextDLat.text.toString().isEmpty()
            || binding.editTextDLng.text.toString().isEmpty()

            || binding.editTextDFDLat.text.toString().isEmpty()
            || binding.editTextDFFLat.text.toString().isEmpty()
            || binding.editTextDFDLng.text.toString().isEmpty()
            || binding.editTextDFFLng.text.toString().isEmpty()
        ) {
            if (needTips) {
                ToastUtil.getInstance().showToast("请输入完整经纬度")
            }
            return
        }

        //[经纬度度分秒弹窗]
        val degreeLat = binding.etMapSearchDegreeLat.text.toString()
        val minuteLat = binding.etMapSearchMinuteLat.text.toString()
        val secondLat = binding.etMapSearchSecondLat.text.toString()
        val degreeLng = binding.etMapSearchDegreeLng.text.toString()
        val minuteLng = binding.etMapSearchMinuteLng.text.toString()
        val secondLng = binding.etMapSearchSecondLng.text.toString()

        //[添加搜索经纬度marker]
        val mapSearchPoi = MapSearchPoi()
        mapSearchPoi.name = "N" + degreeLat + "°" + minuteLat + "′" + secondLat +
                "″ E" + degreeLng + "°" + minuteLng + "′" + secondLng + "″"
        mapSearchPoi.lat = LocationUtils.Dms2D(degreeLat, minuteLat, secondLat)
        mapSearchPoi.lng = LocationUtils.Dms2D(degreeLng, minuteLng, secondLng)
        onItemClick(mapSearchPoi)
    }

    //[adapter点击事件-添加marker]
    fun onItemClick(poiItem: MapSearchPoi) {
        binding.etMapSearchName.text = Editable.Factory.getInstance().newEditable("")
        poiItem.tabType = checkedType.get()

        //[在线搜索——高德需要转换经纬度; isAMapDataAvailable 返回true代表当前位置在大陆、港澳地区，反之不在。大陆使用的是高德GCJ-02坐标系,其他使用的是WGS84]
        if (poiItem.coordType == CustomCoordinateType.GAODE
            && CoordinateTransformUtils.isAMapDataAvailable(poiItem.lat, poiItem.lng)) {
            val latLng = CoordinateTransformUtils.gcj02towgs84(poiItem.lng, poiItem.lat)
            LogUtil.e(TAG, "经纬度转换 转换前:[${poiItem.lat},${poiItem.lng}] ,转换后:[${latLng[1]},${latLng[0]}]")
            poiItem.lng = latLng[0]
            poiItem.lat = latLng[1]
        } else if (poiItem.coordType == CustomCoordinateType.BAIDU) {
            val latLng = CoordinateTransformUtils.bd09towgs84(poiItem.lng, poiItem.lat)
            LogUtil.e(TAG, "经纬度转换 转换前:[${poiItem.lat},${poiItem.lng}] ,转换后:[${latLng[1]},${latLng[0]}]")
            poiItem.lng = latLng[0]
            poiItem.lat = latLng[1]
        }

        MapSearchLayerInstance.getInstance().addItem(poiItem)

        //[点击之后隐藏列表]
        binding.listRootView.visibility = View.GONE
        binding.itemTips.visibility = View.GONE

        //[隐藏键盘]
        CommonUtil.hideKeyboard(dialog)
    }


    //[取消监听]
    override fun onDismiss(dialog: DialogInterface) {
        MapSearchLayerInstance.getInstance().clearMapLayer()
        super.onDismiss(dialog)
        dismissListener?.onDismiss(dialog)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        ImmersionBar.destroy(this)
    }


    //[显示/隐藏弹窗]
    companion object {
        private var dialogRef: WeakReference<MapSearchFragment>? = null
        private var dismissListener: DialogInterface.OnDismissListener? = null

        @JvmStatic
        fun showDialog(
            fragmentManager: FragmentManager,
            checked: Boolean,
            listener: DialogInterface.OnDismissListener
        ) {
            dismissListener = listener
            dismissDialog()
            if (!checked) return
            val searchFragment = MapSearchFragment()
            searchFragment.show(fragmentManager, null)
            dialogRef = WeakReference(searchFragment)
        }

        @JvmStatic
        fun dismissDialog() {
            if (dialogRef?.get()?.dialog?.isShowing == true) {
                dialogRef?.get()?.dismissAllowingStateLoss()
                dialogRef?.clear()
            }
            dialogRef = null
        }
    }


}